package service.impl;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import model.Train;
import service.TrainService;
import dao.TrainDAO;

@Stateless
public class TrainServiceImpl implements TrainService {

	@EJB
	private TrainDAO trainDAO;
	
	@Override
	public List<Train> findAll() {
		return trainDAO.findAll();
	}

	@Override
	public Train findById(Integer id) {
		return trainDAO.find(id);
	}

	@Override
	public String save(Train train) {
		if (trainDAO.findByNumber(train.getTrainNumber()) == null) {
			trainDAO.save(train);
			return "ok";
		}
		return "This train number already exists!";	 
	}

	@Override
	public void delete(Train train) {
		trainDAO.delete(train);
	}

	@Override
	public String update(Train train) {
		Train temp = trainDAO.find(train.getTrainID());
		if (temp != null) {
			Train number = trainDAO.findByNumber(train.getTrainNumber());
			if (number == null) {
				if (temp.getTrainNumber() == train.getTrainNumber()) {
					if (temp.getPlaces() == train.getPlaces()) {
						return "ok";
					} else {
						temp.setPlaces(train.getPlaces());
						trainDAO.update(temp);
						return "ok";
					}		
				}
				temp.setTrainNumber(train.getTrainNumber());
				temp.setPlaces(train.getPlaces());
				trainDAO.update(temp);
				return "ok";
			} else {
				if (number.getTrainID() == temp.getTrainID()) {
					temp.setTrainNumber(train.getTrainNumber());
					temp.setPlaces(train.getPlaces());
					trainDAO.update(temp);
					return "ok";
				} else {
					return "This train number already exists!";	 
				}
			}
		} else {
			return "Train with this id wasn't found, update your list";
		}
	}
	
}
